<template>
  <PageContainer>
    <view class="container">
      <Header title="发送结果" v-model="headerHeight" />
      <view style="position: sticky" :style="'top:' + headerHeight + 'px;'">
        <view class="disFlxJS statisticsBox px-15">
          <view>
            <text class="fw-7">发送总人数: {{ dataList.length }}</text>
            <text class="pl-10 fz-12 tips">成功({{ currentMsgDetails?.sendSuccessNum ?? 0 }})</text>
            <text class="pl-10 fz-12 tips">阅读({{ currentMsgDetails?.readNum ?? 0 }})</text>
          </view>
          <view class="disFlxAC">
            <template v-for="(item, index) in currentMsgDetails?.messageChannelList" :key="index">
              <text
                class="ali-icon ml-15"
                :style="
                  item.messageChannel === SendTypeEnum.SMS ? 'color: #2878ff' : 'color: #07c160'
                "
                :class="item.messageChannel === SendTypeEnum.SMS ? 'fz-16' : 'fz-18'"
              >
                {{ item.messageChannel === SendTypeEnum.SMS ? '&#xe601;' : '&#xe602;' }}
              </text>
            </template>
          </view>
        </view>
        <view class="th tr">
          <view class="td" style="width: 80rpx; flex: none" @click="selectAll">
            <image
              :style="!isAllChecked ? 'display:block;' : 'display:none;'"
              src="https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/saas/icon/radio.png"
              style="width: 30rpx; height: 30rpx"
            />
            <image
              :style="isAllChecked ? 'display:block;' : 'display:none;'"
              src="https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/saas/icon/radio-checked2.png"
              style="width: 30rpx; height: 30rpx"
            />
          </view>
          <view class="td">
            <text>姓名</text>
          </view>
          <view class="td">
            <FormSelector
              v-model="params.position"
              :localdata="levelList"
              :border="false"
              @change="getMessageSendResultList"
            >
              <template #content>
                <text>职务</text>
                <text class="ali-icon ml-2">&#xe8f2;</text>
              </template>
            </FormSelector>
          </view>
          <view class="td">
            <FormSelector
              v-model="params.sendStatus"
              :localdata="statusList"
              :border="false"
              @change="getMessageSendResultList"
            >
              <template #content>
                <text>状态</text>
                <text class="ali-icon ml-2">&#xe8f2;</text>
              </template>
            </FormSelector>
          </view>
          <view class="td">
            <FormSelector
              v-model="params.readStatus"
              :localdata="readList"
              :border="false"
              @change="getMessageSendResultList"
            >
              <template #content>
                <text>阅读</text>
                <text class="ali-icon ml-2">&#xe8f2;</text>
              </template>
            </FormSelector>
          </view>
        </view>
      </view>

      <view>
        <view class="tr" v-for="(item, index) in dataList" :key="index" @click="openPopup(item)">
          <view class="td" style="width: 80rpx; flex: none" @click.stop="changeChecked(item)">
            <image
              :style="!isChecked(item) ? 'display:block;' : 'display:none;'"
              src="https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/saas/icon/radio.png"
              style="width: 30rpx; height: 30rpx"
            />
            <image
              :style="isChecked(item) ? 'display:block;' : 'display:none;'"
              src="https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/saas/icon/radio-checked2.png"
              style="width: 30rpx; height: 30rpx"
            />
          </view>
          <view class="td">{{ item.recipientName }}</view>
          <view class="td">{{ item.position }}</view>
          <view class="td" :style="getSendStatusVal(item)?.style">
            {{ getSendStatusVal(item)?.text ?? '' }}
          </view>
          <view class="td" :style="getReadStatusVal(item).style">
            {{ getReadStatusVal(item).text }}
          </view>
        </view>
      </view>

      <TButtonGroup position="fixed" :styles="{ backgroundColor: '#FFF', display: 'block' }">
        <template #header>
          <view class="gridBox">
            <view
              v-for="(item, index) in totalBtnList"
              :key="index"
              class="disFlxCC gridItem"
              :class="{ active: item.checked }"
              @click="item.selectAll"
            >
              <view class="fw-7 num">{{ item.num }}</view>
              <view class="pt-4 label">{{ item.label }}</view>
              <image
                src="https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/saas/icon/radio-checked2.png"
                style="width: 28rpx; height: 28rpx"
                class="checkedImg"
              />
            </view>
          </view>
        </template>
        <TButton
          class="gutter-btn"
          type="primary"
          :text="`发送选中人员（${checkedList.length}）`"
          @click="resetSend"
        />
      </TButtonGroup>

      <UniPopup ref="showPopupRef" :isMaskClick="true">
        <view class="bgf pa-24 br-16 popupBox">
          <view class="title fz-16 mb-16">信息接收状态</view>
          <view class="disFlxAC">
            <view class="imgBox shrink0">
              <TImage
                :src="activeUserInfo.avatar"
                width="96rpx"
                height="96rpx"
                borderRadius="50%"
              />
            </view>
            <view class="ml-12" style="flex: 1">
              <view class="disFlxAC">
                <view class="fz-16 fw-7 ov-1">{{ activeUserInfo.recipientName }}</view>
                <view class="fz-12 pl-4 label shrink0">
                  {{ activeUserInfo?.companyPosition ?? '' }}
                </view>
              </view>
              <view class="fz-12 mt-4 label ov-1" v-if="activeUserInfo?.position">
                {{ activeUserInfo.position }}
              </view>
              <view class="fz-12 mt-4 label ov-1">{{ activeUserInfo.companyName }}</view>
            </view>
            <view
              v-if="activeUserInfo.phoneNumber"
              class="phoneBox shrink0 ml-10"
              @click="makePhoneCall"
            >
              <text class="ali-icon fz-18">&#xe678;</text>
            </view>
          </view>
          <view
            class="disFlx mt-12"
            v-for="item in activeUserInfo.messageChannelInfoList"
            :key="item.messageChannel"
          >
            <view class="label" style="width: 200rpx">
              {{ item.messageChannel === SendTypeEnum.WECHAT ? '微信公众号：' : '手机短信：' }}
            </view>
            <!-- <view v-if="item.sendStatus === SendStatusEnum.ERROR" :style="getSendStatusVal(item)?.style">{{ item.remark }}</view> -->
            <view :style="getSendStatusVal(item)?.style">
              {{ getSendStatusVal(item)?.text ?? '' }}
            </view>
          </view>
          <view class="disFlx mt-12">
            <view class="label" style="width: 200rpx">阅读状态：</view>
            <view class="label">
              {{ activeUserInfo.readStatus === ReadStatusEnum.READ ? '已阅读' : '暂未阅读' }}
            </view>
          </view>
        </view>
      </UniPopup>
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /* messageSendResult 发送结果  */
  import PageContainer from '@/components/PageContainer/index.vue';
  import Header from '@/components/Header/index.vue';
  import { computed, ref, unref, watch, reactive, getCurrentInstance } from 'vue';
  import TButtonGroup from '@/components/TButtonGroup/index.vue';
  import TButton from '@/components/TButtonGroup/TButton.vue';
  import FormSelector from '@/components/Form/components/FormSelector.vue';
  import type { Localdata } from '@/components/Form/types';

  import { getMessageSendResult } from '@/api/admin';
  import type { SearchResultData, ResultListData } from '@/api/admin/types';
  import { navigateTo, onLoad } from '@/router';
  import { useAdminStoreWithOut } from '@/store/modules/admin';
  import { SendTypeEnum, SendStatusEnum, ReadStatusEnum } from '@/enums/admin';
  import { getDownStatisticsList } from '@/api';
  import type { GetDownStatisticsListResult } from '@/api/indexTypes';
  import { uniqBy } from 'lodash-es';
  import UniPopup from '@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue';
  import TImage from '@/components/TImage/index.vue';

  const headerHeight = ref(0);
  const { currentMsgDetails } = useAdminStoreWithOut(); // 消息详情

  const levelList = ref<Localdata[]>([]);
  onLoad(async (op) => {
    params.unionMsgId = op.unionMsgId;
    // 获取职务
    getDownStatisticsList().then((_r: GetDownStatisticsListResult[]) => {
      levelList.value = _r.map((v) => {
        return {
          value: v.name,
          text: v.name,
        };
      });
      levelList.value.unshift({
        value: '',
        text: '全部',
      });
    });
    // 获取初始数据
    getMessageSendResultList('init');
  });

  // 查询结果
  const params = reactive<SearchResultData>({
    unionMsgId: '',
    position: undefined, // 职务
    sendStatus: undefined, // 发送状态
    readStatus: undefined, // 已读状态
  });

  const oldDataList = ref<ResultListData[]>([]); // 所有用户
  const checkedList = ref<ResultListData[]>([]); // 勾选用户
  const dataList = ref<ResultListData[]>([]); // 筛选用户
  const errList = ref<ResultListData[]>([]); // 筛选用户中发送失败的
  const unClickList = ref<ResultListData[]>([]); // 筛选用户中未点击的

  const getMessageSendResultList = async (type?: string) => {
    const _r = await getMessageSendResult(params);
    dataList.value = _r;
    errList.value = _r.filter((v: any) => v.sendStatus === SendStatusEnum.ERROR);
    unClickList.value = _r.filter((v: any) => v.readStatus === ReadStatusEnum.UNREAD);
    initButton();
    if (type === 'init') {
      // 首次调用
      oldDataList.value = _r;
    }
  };

  // 判断是否选中
  const isChecked = (item: ResultListData) => {
    const checkedObj = unref(checkedList).find(
      (v: ResultListData) => v.recipientId === item.recipientId,
    );
    return checkedObj ? true : false;
  };
  // 勾选|| 取消勾选
  const changeChecked = (item: ResultListData) => {
    if (isChecked(item)) {
      checkedList.value = unref(checkedList).filter((v: ResultListData) => {
        return v.recipientId !== item.recipientId;
      });
    } else {
      checkedList.value.push(item);
    }
  };
  // 判断当前列表是否全选
  const isAllChecked = computed(() => {
    for (let i = 0; i < unref(dataList).length; i++) {
      const item = unref(dataList)[i];
      const checkedObj = unref(checkedList).find(
        (v: ResultListData) => v.recipientId === item.recipientId,
      );
      if (!checkedObj) {
        return false;
      }
    }
    return true;
  });
  // 全选 || 取消全选 当前筛选用户
  const selectAll = () => {
    if (unref(isAllChecked)) {
      cancelSelect();
    } else {
      let _list = [...unref(checkedList), ...unref(dataList)];
      checkedList.value = uniqBy(_list, 'recipientId'); // 选择用户去重
    }
  };
  // 取消当前筛选数据的选中状态
  const cancelSelect = () => {
    for (let i = 0; i < unref(checkedList).length; i++) {
      const item = unref(checkedList)[i];
      const checkedObj = unref(dataList).find(
        (v: ResultListData) => v.recipientId === item.recipientId,
      );
      if (checkedObj) {
        checkedList.value.splice(i, 1);
        i--;
      }
    }
  };

  // 判断发送失败 在当前列表是否全选
  const isErrAllChecked = computed(() => {
    for (let i = 0; i < unref(errList).length; i++) {
      const item = unref(errList)[i];
      const checkedObj = unref(checkedList).find(
        (v: ResultListData) => v.recipientId === item.recipientId,
      );
      if (!checkedObj) {
        return false;
      }
    }
    return true;
  });
  // 判断未点击 在当前列表是否全选
  const isUnclickAllChecked = computed(() => {
    for (let i = 0; i < unref(unClickList).length; i++) {
      const item = unref(unClickList)[i];
      const checkedObj = unref(checkedList).find(
        (v: ResultListData) => v.recipientId === item.recipientId,
      );
      if (!checkedObj) {
        return false;
      }
    }
    return true;
  });

  // 底部按钮相关
  watch(
    () => unref(checkedList),
    (val) => {
      initButton();
    },
    {
      deep: true,
    },
  );

  interface BtnData {
    num: number;
    label: string;
    checked: boolean;
    selectAll: () => void;
  }
  const totalBtnList = ref<BtnData[]>([]);
  const initButton = function () {
    totalBtnList.value = [
      {
        num: unref(dataList).length,
        label: '全部',
        checked: unref(isAllChecked),
        selectAll: function () {
          selectAll();
        },
      },
      {
        num: unref(errList).length,
        label: '发送失败',
        checked: unref(isAllChecked) || !unref(errList).length ? false : unref(isErrAllChecked),
        selectAll: function () {
          if (unref(errList).length) {
            cancelSelect(); // 取消当前筛选的选中
            let _list = [...unref(checkedList), ...unref(errList)];
            checkedList.value = uniqBy(_list, 'recipientId'); // 选择用户去重
          }
        },
      },
      {
        num: unref(unClickList).length,
        label: '未阅读',
        checked:
          unref(isAllChecked) || !unref(unClickList).length ? false : unref(isUnclickAllChecked),
        selectAll: function () {
          if (unref(unClickList).length) {
            cancelSelect(); // 取消当前筛选的选中
            let _list = [...unref(checkedList), ...unref(unClickList)];
            checkedList.value = uniqBy(_list, 'recipientId'); // 选择用户去重
          }
        },
      },
    ];
  };

  interface StatusData extends Localdata {
    style: string;
  }
  const statusList = ref<StatusData[]>([
    {
      value: '',
      text: '全部',
      style: 'color: #333333',
    },
    {
      value: SendStatusEnum.SUCCESS,
      text: '成功',
      style: 'color: #07c160',
    },
    {
      value: SendStatusEnum.ERROR,
      text: '失败',
      style: 'color: #EA5E0E',
    },
    // {
    //   value: SendStatusEnum.UNSENT,
    //   text: '未发送',
    //   style: 'color: #aaabab',
    // },
    {
      value: SendStatusEnum.SENDIN,
      text: '发送中',
      style: 'color: #2878FF',
    },
  ]);

  const getSendStatusVal = (item: ResultListData) => {
    if (item.sendStatus === SendStatusEnum.JAVASUCCESS) {
      return {
        value: SendStatusEnum.SUCCESS,
        text: '成功',
        style: 'color: #07c160',
      };
    }
    return unref(statusList).find((v) => v.value === item.sendStatus);
  };
  const readList = ref<Localdata[]>([
    {
      value: '',
      text: '全部',
    },
    {
      value: ReadStatusEnum.READ,
      text: '已阅读',
    },
    {
      value: ReadStatusEnum.UNREAD,
      text: '未阅读',
    },
  ]);
  const getReadStatusVal = (item: ResultListData) => {
    if (item.readStatus === ReadStatusEnum.READ) {
      return {
        text: '是',
        style: 'color: #EA5E0E',
      };
    } else {
      return {
        text: '否',
        style: 'color: #aaabab',
      };
    }
  };

  // 打开消息接收状态
  const activeUserInfo = ref({} as ResultListData);
  const _this = getCurrentInstance();
  const openPopup = (item: ResultListData) => {
    activeUserInfo.value = item;
    (_this?.refs['showPopupRef'] as any).open('center');
  };

  const makePhoneCall = () => {
    uni.makePhoneCall({ phoneNumber: unref(activeUserInfo).phoneNumber as string });
  };

  // 重新发送
  const resetSend = () => {
    if (!unref(checkedList).length) return;
    // typeId === 11 || typeId === 16 控制入会缴费或者续费则指定发送人员,否则则根据条件调用用户
    let typeId = currentMsgDetails?.typeId === 11 || currentMsgDetails?.typeId === 16 ? currentMsgDetails?.typeId : undefined;
    navigateTo({
      name: 'addMessage',
      options: { userIds: checkedList.value.map((v) => v.recipientId), typeId},
    });
  };
</script>

<style lang="scss" scoped>
  .container {
    font-size: 28rpx;
    .statisticsBox {
      background-color: #fff4e7;
      height: 88rpx;
      .tips {
        color: #aaabab;
      }
    }

    .tr {
      padding: 0 30rpx;
      display: flex;
      align-items: center;
      background-color: #fff;
      .td {
        height: 88rpx;
        flex: 1;
        flex-shrink: 0;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .td.alignLeft {
        justify-content: flex-start;
      }
    }
    .th.tr {
      font-weight: 700;
      border-bottom: solid 1px #f5f5f5;
    }

    .gridBox {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      column-gap: 20rpx;
      margin-bottom: 30rpx;
      .gridItem {
        border-radius: 16rpx;
        background-color: #f7f8fa;
        border: solid 1px #f7f8fa;
        height: 104rpx;
        position: relative;
        .num {
          color: #333;
        }
        .label {
          color: #aaabab;
        }
        .checkedImg {
          position: absolute;
          right: 6rpx;
          top: 6rpx;
          opacity: 0;
          transition: opacity 0.2s;
        }
      }
      .gridItem.active {
        background-color: #d0f7ff;
        border: solid 1px #2878ff;
        .num,
        .label {
          color: #2878ff;
        }
        .checkedImg {
          opacity: 1;
        }
      }
    }
    .popupBox {
      width: 600rpx;
      box-sizing: border-box;
      .title {
        text-align: center;
      }
      .imgBox {
        position: relative;
        .levelBox {
          position: absolute;
          bottom: 0;
          left: 50%;
          transform: translate(-50%, 20%);
          color: #fff;
          background-color: #2878ff;
          white-space: nowrap;
        }
      }
      .label {
        color: #aaabab;
      }
      .shrink0 {
        flex-shrink: 0;
      }
      .phoneBox {
        background-color: #21bab5;
        border-radius: 50%;
        color: #fff;
        width: 72rpx;
        height: 72rpx;
        text-align: center;
        line-height: 72rpx;
      }
    }
  }
</style>
